package com.xbongbong.config;

import com.xbongbong.parent.interfaces.DynamicStrategy;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2023/01/05 16:02
 */
@Component
public class BusinessDynamicStrategyConfig implements ApplicationContextAware {

    private Map<String, DynamicStrategy> dynamicStrategyMap;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        dynamicStrategyMap = applicationContext.getBeansOfType(DynamicStrategy.class);
    }

    @Bean("typeToDynamicStrategyMap")
    public Map<Integer, DynamicStrategy> typeToDynamicStrategyMap() {
        Map<Integer, DynamicStrategy> map = new HashMap<>(dynamicStrategyMap.size());
        dynamicStrategyMap.forEach((beanName, dynamicStrategy) -> {
            if (Objects.isNull(dynamicStrategy.type())) {
                map.put(null, dynamicStrategy);
            } else {
                for (Integer businessType : dynamicStrategy.type()) {
                    map.put(businessType, dynamicStrategy);
                }
            }
        });
        return map;
    }
}
